﻿namespace BadHabit.WPFTools
{
    using System;
    using System.Windows.Automation;
    using System.Windows.Automation.Peers;
    using System.Windows.Automation.Provider;

    public class NumericUpDownAutomationPeer : FrameworkElementAutomationPeer, IRangeValueProvider
    {
        public NumericUpDownAutomationPeer(NumericUpDown control)
            : base(control)
        {
        }

        protected override string GetClassNameCore()
        {
            return "NumericUpDown";
        }

        protected override AutomationControlType GetAutomationControlTypeCore()
        {
            return AutomationControlType.Spinner;
        }

        public override object GetPattern(PatternInterface patternInterface)
        {
            if (patternInterface == PatternInterface.RangeValue)
            {
                return this;
            }

            return base.GetPattern(patternInterface);
        }

        internal void RaiseValueChangedEvent(decimal oldValue, decimal newValue)
        {
            this.RaisePropertyChangedEvent(RangeValuePatternIdentifiers.ValueProperty, (double)oldValue, (double)newValue);
        }

        #region IRangeValueProvider Members

        bool IRangeValueProvider.IsReadOnly
        {
            get
            {
                return !IsEnabled();
            }
        }

        double IRangeValueProvider.LargeChange
        {
            get
            {
                return (double)this.MyOwner.Change;
            }
        }

        double IRangeValueProvider.Maximum
        {
            get
            {
                return (double)this.MyOwner.Maximum;
            }
        }

        double IRangeValueProvider.Minimum
        {
            get
            {
                return (double)this.MyOwner.Minimum;
            }
        }

        void IRangeValueProvider.SetValue(double value)
        {
            if (!this.IsEnabled())
            {
                throw new ElementNotEnabledException();
            }

            decimal val = (decimal)value;

            if (val < this.MyOwner.Minimum || val > this.MyOwner.Maximum)
            {
                throw new ArgumentOutOfRangeException("value");
            }

            this.MyOwner.Value = val;
        }

        double IRangeValueProvider.SmallChange
        {
            get
            {
                return (double)this.MyOwner.Change;
            }
        }

        double IRangeValueProvider.Value
        {
            get
            {
                return (double)this.MyOwner.Value;
            }
        }

        #endregion

        private NumericUpDown MyOwner
        {
            get
            {
                return (NumericUpDown)this.Owner;
            }
        }
    }
}
